package com.example.delll.kugou.utils;

import android.os.Handler;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttp {


    private static final OkHttpClient okHttpClient = new OkHttpClient();
    private static final String TAG = "MainActivity";
//    public static final String a1="http://c.m.163.com/recommend/getSubDocPic?tid=T1348647909107&from=toutiao&offset=0&size=10&fn=1&LastStdTime=0&spestr=reader_expert_1&prog=&passport=&devId=VwZ88tRL3zASBaVO92NpAUcjKt2AR8TTp2exHkpfIdcWqJZAm118cFHgsgr1v9IF&lat=&lon=&version=44.0&net=wifi&ts=1538630726&sign=SZ6rcYxamgySJrYSCnpv7%2BS%2BneZt%2FOZTyboKXx%2FIDRV48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=miliao_news&mac=dXwqerbKhS6i17lVzCeBnHbpt7PSWbUoS%2FM7z6UHeeU%3D&open=&openpath=";
    public static final String a1="http://bjrec.m.163.com/flow/recsys/getComRecNews?tid=T1348648517839&from=T1348648517839&offset=0&size=10&fn=1&LastStdTime=0&passport=&devId=VwZ88tRL3zASBaVO92NpAUcjKt2AR8TTp2exHkpfIdcWqJZAm118cFHgsgr1v9IF&lat=&lon=&version=44.0&net=wifi&ts=1538805690&sign=yfoYKA6m5A3Uny8Ig0XwuElzzxGQYm4jCQr0Ys4IOsp48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=miliao_news&mac=dXwqerbKhS6i17lVzCeBnHbpt7PSWbUoS%2FM7z6UHeeU%3D&open=&openpath=";

    private OkHttp() {
    }

    private final static Handler h = new Handler() {};

  public interface OkHttpUtils {

        void onFailure(IOException e);

        void onResponse(String json);
    }

    public static void getJson(String url, final OkHttpUtils okHttpUtils) {
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        okHttpUtils.onFailure(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                InputStream inputStream = response.body().byteStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                final StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        okHttpUtils.onResponse(sb.toString());
                    }
                });
            }
        });
    }

}
